//
//  DownViewController.m
//  svqj
//
//  Created by xftt on 14-7-2.
//
//

#import "DownViewController.h"
#import "QJDown.h"
#import "QJUpData.h"
#import "MainViewController.h"

@interface DownViewController ()
{
    BOOL isShow;
    UIView *_upDataView;
    UIView *bgListView;
    UIScrollView *listView;
    NSMutableArray *upList;
}

@end

@implementation DownViewController
{
    NSMutableArray *_QJData;
    UIScrollView *_scroll;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    _scroll = [[UIScrollView alloc]initWithFrame:_contentView.bounds];
    [_contentView addSubview:_scroll];
    
    _upDataView = [[UIView alloc] initWithFrame:CGRectMake(85, 8, 8, 8)];
    [_upDataView setBackgroundColor:[UIColor colorWithHexString:@"#bb0000"]];
    _upDataView.layer.cornerRadius = 4;
    [_upDataView setUserInteractionEnabled:NO];
    [_upDataView setHidden:YES];
    [_editButton addSubview:_upDataView];
    if ([((MainViewController*)self.tabFrameController).update count]>0) {
        [_upDataView setHidden:NO];
    }
    [_editButton setTitle:@"更新列表" forState:UIControlStateNormal];
    [_editButton addTarget:self action:@selector(showUpDataList) forControlEvents:UIControlEventTouchUpInside];
    
    bgListView = [[UIView alloc]initWithFrame:_contentView.bounds];
    [bgListView setBackgroundColor:[UIColor blackColor]];
    [bgListView setAlpha:0];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showUpDataList)];
    [bgListView addGestureRecognizer:tap];
    [_contentView addSubview:bgListView];
    
    listView = [[UIScrollView alloc] initWithFrame:CGRectMake(_contentView.bounds.size.width, 0, 240, _contentView.bounds.size.height)];
    [listView setBackgroundColor:[UIColor colorWithHexString:@"#555555"]];
    [_contentView addSubview:listView];
    
    [FilesDownManage sharedFilesDownManage].downloadDelegate = self;
}

- (void)showUpDataList
{
    if (!isShow) {
        [self loadUpDataList];
        [UIView animateWithDuration:0.2
                         animations:^{
                             [bgListView setAlpha:0.1];
                             [listView setFrameX:_contentView.bounds.size.width-240];
                         } completion:^(BOOL finished){
                         }];
    }
    else
    {
        [UIView animateWithDuration:0.2
                         animations:^{
                             [bgListView setAlpha:0];
                             [listView setFrameX:_contentView.bounds.size.width];
                         } completion:^(BOOL finished){
                         }];
    }
    isShow = !isShow;
}

-(void)viewWillAppear:(BOOL)animated
{
    FilesDownManage *filedownmanage = [FilesDownManage sharedFilesDownManage];
    [filedownmanage startLoad];
    self.downingList=filedownmanage.downinglist;
    [self loadDowningList];
    
    if ([((MainViewController*)self.tabFrameController).update count]>0) {
        [self showUpDataList];
    }
}

-(void)viewWillDisappear:(BOOL)animated{
    isShow = YES;
    [self showUpDataList];
}

//加载有更新的全景列表
-(void)loadUpDataList
{
    [listView removeSubviews];
    upList =((MainViewController*)self.tabFrameController).update;
    for (int i=0; i<[upList count]; i++) {
        QJUpData *upItem = [[QJUpData alloc]initWithFrame:CGRectMake(0, i*92+2, 240, 91)];
        [listView addSubview:upItem];
        
        QuanJing *qj = [[QuanJing alloc]initWithDictionary:[upList objectAtIndex:i]];
        
        NSString* docPath = [NSHomeDirectory() stringByAppendingPathComponent: @"Documents"];
        NSString* imagePath = [NSString stringWithFormat: @"%@/SVQJ/%@/qjicon.png", docPath, qj.sid];
        [upItem.imgvQJ setImage:[UIImage imageWithData:[NSData dataWithContentsOfFile:imagePath]]];
        [upItem.lbTltle setText:qj.title];
        [upItem.btnUpData setTag:i];
        [upItem.btnUpData addTarget:self action:@selector(upDataQJ:) forControlEvents:UIControlEventTouchUpInside];
    }
    CGSize size = CGSizeMake(240,[upList count]*92<698?699:[upList count]*92);
    [listView setContentSize:size];
}

-(void)upDataQJ:(UIButton*)sender
{
    QuanJing *qj = [[QuanJing alloc]initWithDictionary:[upList objectAtIndex:sender.tag]];
    
    NSUserDefaults *_Data = [NSUserDefaults standardUserDefaults];
    NSMutableArray *old = [NSMutableArray arrayWithArray:[_Data objectForKey:@"QJData"]];
    NSMutableArray *oldT = [NSMutableArray arrayWithArray:[_Data objectForKey:@"QJTemp"]];
    NSMutableArray *new = [NSMutableArray arrayWithArray:old];
    NSMutableArray *newT = [NSMutableArray arrayWithArray:oldT];
    
    
    //删除全景文件夹
    NSString* docPath = [NSHomeDirectory() stringByAppendingPathComponent: @"Documents"];
    NSString* savePath = [NSString stringWithFormat: @"%@/SVQJ/%@", docPath, qj.sid];
    if ([[NSFileManager defaultManager] fileExistsAtPath:savePath]) {
        [[NSFileManager defaultManager] removeItemAtPath:savePath error:nil];
    }
    
    //删除全景记录
    for (int i=0; i<[old count]; i++) {
        if ([qj.sid isEqualToString:[[old objectAtIndex:i] objectForKey:@"sid"]]) {
            [new removeObjectAtIndex:i];
        }
    }
    for (int i=0; i<[oldT count]; i++) {
        if ([qj.sid isEqualToString:[[oldT objectAtIndex:i] objectForKey:@"sid"]]) {
            [newT removeObjectAtIndex:i];
        }
    }
    
    [_Data setObject:new forKey:@"QJData"];
    [_Data setObject:newT forKey:@"QJTemp"];
    [_Data synchronize];
    
    //下载更新
    [[FilesDownManage sharedFilesDownManage]downFile:qj];
    
    //从更新列表删除
    [upList removeObjectAtIndex:sender.tag];
    
    //更新状态
    if ([((MainViewController*)self.tabFrameController).update count]>0) {
        [_upDataView setHidden:NO];
    }
    
    [(MainViewController*)self.tabFrameController showUpdataNum];
    
    [self loadUpDataList];
    [self loadDowningList];
}

//加载下载中的全景
-(void)loadDowningList
{
    [_scroll removeSubviews];
    for (int i=0; i<[self.downingList count]; i++) {
        ASIHTTPRequest *theRequest=[self.downingList objectAtIndex:i];
        if (theRequest==nil) {
            return;
        }
        FileModel *fileInfo=[theRequest.userInfo objectForKey:@"File"];
        
        NSString *currentsize = [CommonHelper getFileSizeString:fileInfo.fileReceivedSize];
        
        QuanJing* quanjing = [[QuanJing alloc] initWithDictionary:fileInfo.quanjing];
        
        QJDown* item = [self getViewWithQuanJing:quanjing AndIndex:[self.downingList count]-(i+1)];
        item.fileInfo = fileInfo;
        item.request = theRequest;
        
        if ([currentsize longLongValue]==0) {
        }else
        {
            [item setProgressLoad:[fileInfo.fileSize floatValue] withNow:[currentsize floatValue]];
        }
        [item setProgressLoad:[fileInfo.fileSize floatValue] withNow:[currentsize floatValue]];
        
        item.lbLoad.text =[NSString stringWithFormat:@"%@/%@",[CommonHelper getFileSizeString:currentsize],[CommonHelper getFileSizeString:fileInfo.fileSize]];
        
        [item.btnEsc addTarget:self action:@selector(deleteFile:) forControlEvents:UIControlEventTouchUpInside];
        [item.btnEsc setTag:i];
        [item.btnStop setTag:i];
        [item.btnStop addTarget:self action:@selector(stopDownFile:) forControlEvents:UIControlEventTouchUpInside];
        
        if(fileInfo.isDownloading)//文件正在下载
        {
            [item.btnStop setTitle:@"暂停" forState:UIControlStateNormal];
            [item.btnStop.titleLabel setTextColor:[UIColor colorWithHexString:@"#AAAAAA"]];
        }
        else if(!fileInfo.isDownloading && !fileInfo.willDownloading&&!fileInfo.error)
        {
            item.lbLoad.text = @"暂停";
            [item.btnStop setTitle:@"继续" forState:UIControlStateNormal];
            [item.btnStop.titleLabel setTextColor:[UIColor colorWithHexString:@"#AAAAAA"]];
        }else if(!fileInfo.isDownloading && fileInfo.willDownloading&&!fileInfo.error)
        {
            item.lbLoad.text = @"等待";
            [item.btnStop setTitle:@"继续" forState:UIControlStateNormal];
        }else if (fileInfo.error)
        {
            item.lbLoad.text = @"错误";
            [item.btnStop setTitle:@"重试" forState:UIControlStateNormal];
        }
        if (fileInfo.isUnzip) {
            item.lbLoad.text = @"安装中...";
        }
        [_scroll addSubview:item];
    }
    
    CGSize size = CGSizeMake(_scroll.frame.size.width, (([self.downingList count]-1)/3+1)*320+42<698?699:(([self.downingList count]-1)/3+1)*320+42);
    [_scroll setContentSize:size];
}

- (QJDown *)getViewWithQuanJing:(QuanJing*)qj AndIndex:(NSInteger)index
{
    NSInteger line = index/3;
    NSInteger row = index-line*3;
    
    QJDown *item = [[QJDown alloc] initWithFrame:CGRectMake(42+262*row, 40+320*line, 236, 270)];
    [item setQuanjing:qj];
    item.imgvQJ.tag = index;
    return item;
}


-(void)updateCellOnMainThread:(FileModel *)fileInfo
{
    NSArray *items = [_scroll subviews];
    for(id obj in items)
    {
        if ([obj isKindOfClass:[QJDown class]]) {
            QJDown *item = (QJDown*)obj;
            if ([item.fileInfo.fileID isEqualToString: fileInfo.fileID]) {
                NSString *currentsize;
                if (fileInfo.post) {
                    currentsize = fileInfo.fileUploadSize;
                }else
                {
                    currentsize = fileInfo.fileReceivedSize;
                }
                
                [item setProgressLoad:[fileInfo.fileSize floatValue] withNow:[currentsize floatValue]];
                
                item.lbLoad.text =[NSString stringWithFormat:@"%@/%@",[CommonHelper getFileSizeString:currentsize],[CommonHelper getFileSizeString:fileInfo.fileSize]];
                if(fileInfo.isDownloading)//文件正在下载
                {
                    if ([currentsize floatValue]==[fileInfo.fileSize floatValue]) {
                        item.lbLoad.text = @"安装中...";
                    }
                    [item.btnStop setTitle:@"暂停" forState:UIControlStateNormal];
                    [item.btnStop.titleLabel setTextColor:[UIColor colorWithHexString:@"#AAAAAA"]];
                }
                else if(!fileInfo.isDownloading && !fileInfo.willDownloading&&!fileInfo.error)
                {
                    item.lbLoad.text = @"暂停";
                    [item.btnStop setTitle:@"继续" forState:UIControlStateNormal];
                    [item.btnStop.titleLabel setTextColor:[UIColor colorWithHexString:@"#AAAAAA"]];
                }else if(!fileInfo.isDownloading && fileInfo.willDownloading&&!fileInfo.error)
                {
                    item.lbLoad.text = @"等待";
                    [item.btnStop setTitle:@"继续" forState:UIControlStateNormal];
                }else if (fileInfo.error)
                {
                    item.lbLoad.text = @"错误";
                    [item.btnStop setTitle:@"重试" forState:UIControlStateNormal];
                }
            }
        }
    }
}

-(void)stopDownFile:(UIButton*)sender
{
    FilesDownManage *filedownmanage = [FilesDownManage sharedFilesDownManage];
    ASIHTTPRequest *theRequest=[self.downingList objectAtIndex:sender.tag];
    FileModel *fileInfo=[theRequest.userInfo objectForKey:@"File"];
    if(fileInfo.isDownloading)//文件正在下载，点击之后暂停下载 有可能进入等待状态
    {
        [sender setTitle:@"继续" forState:UIControlStateNormal];
        [sender.titleLabel setTextColor:[UIColor colorWithHexString:@"#AAAAAA"]];
        [filedownmanage stopRequest:theRequest];
    }
    else
    {
        [sender setTitle:@"暂停" forState:UIControlStateNormal];
        [sender.titleLabel setTextColor:[UIColor colorWithHexString:@"#AAAAAA"]];
        if (fileInfo.post) {
        }else{
            [filedownmanage resumeRequest:theRequest];
        }
    }
    [self loadDowningList];
}

-(void)deleteFile:(UIButton*)sender
{
    FilesDownManage *filedownmanage = [FilesDownManage sharedFilesDownManage];
    ASIHTTPRequest *theRequest=[self.downingList objectAtIndex:sender.tag];
    [filedownmanage deleteRequest:theRequest];
    self.downingList = [FilesDownManage sharedFilesDownManage].downinglist;
    [self loadDowningList];
}

#pragma mark --- updateUI delegate ---
-(void)startDownload:(ASIHTTPRequest *)request
{
    NSLog(@"-------开始下载!");
}

-(void)updateCellProgress:(ASIHTTPRequest *)request
{
    FileModel *fileInfo=[request.userInfo objectForKey:@"File"];
    [self performSelectorOnMainThread:@selector(updateCellOnMainThread:) withObject:fileInfo waitUntilDone:YES];
}

-(void)finishedDownload:(ASIHTTPRequest *)request
{
    [self loadDowningList];
}

-(void)errForUnzip:(ASIHTTPRequest *)request
{
    FileModel *fileInfo=[request.userInfo objectForKey:@"File"];
    NSString *filename = [[QuanJing alloc] initWithDictionary:fileInfo.quanjing].title;
    MainViewController *main = (MainViewController*)self.tabFrameController;
    [main showUnzipErr:filename];
    [self loadDowningList];
}

-(void)ReloadDownLoadingView
{
    self.downingList = [FilesDownManage sharedFilesDownManage].downinglist;
    [self loadDowningList];
}

-(void)allowNextRequest
{
    
}

@end
